#!/bin/bash -e

shopt -s expand_aliases

# cross-OS compatibility (greadlink, gsed, zcat are GNU implementations for OS X)
[[ `uname` == 'Darwin' ]] && {
	which greadlink gsed gzcat > /dev/null && {
		unalias readlink sed zcat
		alias readlink=greadlink sed=gsed zcat=gzcat
	} || {
		echo 'ERROR: GNU utils required for Mac. You may use homebrew to install them: brew install coreutils gnu-sed'
		exit 1
	}
}

declare -r SCRIPT_DIR=$(dirname $(readlink -f "${BASH_SOURCE[0]}"))
function die()
{
    echo -e "\e[0;31m[ERROR]\e[m $1" >&2
    exit ${2:-255}
}

# git subtree add -P gtest https://gitee.com/mirrors/googletest.git HEAD --squash
gtestpath=gtest

# dev tool set
dev_toolset=$(ls -d /opt/rh/devtoolset-* | sort -n -r | head -1)
if [ -n "${dev_toolset}" ]; then
    source ${dev_toolset}/enable
fi

GCC=$(which g++)

cd ${SCRIPT_DIR}

if [ ! -e "${gtestpath}" ]
then
    die "${gtestpath} not found."

    if [ ! -d "${gtestpath}" ]
    then
        die "${gtestpath} not a dir"
    fi
fi

pwd
(pwd && cd ${gtestpath} && [ -d build ] || mkdir build && cd build && cmake .. && make)

if [ $? == 0 ]
then
    echo -e "export GTEST_INC=$(readlink -f ${gtestpath}/googletest/include)\nexport GTEST_LIB=$(readlink -f ${gtestpath}/build/lib)\nexport GTEST_MAIN=$(readlink -f ${gtestpath}/googletest/src/gtest_main.cc)" > gtest.env.sh
    echo 'function gtestcmd() { cmd="'"${GCC}"' -std=c++14 -o a.out $@ -DGTEST ${GTEST_MAIN} -I${GTEST_INC} -L${GTEST_LIB} -lgtest -pthread"; echo "${cmd}" }' >> gtest.env.sh
    echo 'function gtestbuild() { cmd="'"${GCC}"' -std=c++14 -o a.out $@ -DGTEST ${GTEST_MAIN} -I${GTEST_INC} -L${GTEST_LIB} -lgtest -pthread"; echo "${cmd}"; eval "${cmd}" }' >> gtest.env.sh
    echo 'function gtestrun() { cmd="'"${GCC}"' -std=c++14 -o a.out $@ -DGTEST ${GTEST_MAIN} -I${GTEST_INC} -L${GTEST_LIB} -lgtest -pthread"; echo "${cmd}"; eval "${cmd}" && ./a.out }' >> gtest.env.sh
    echo 'env | egrep "GTEST_[^=]+"' >> gtest.env.sh
    ls -l $(readlink -f gtest.env.sh)
else
    echo "failed!"
fi

